package com.carful.xigua.modules.common.security;

import com.carful.xigua.modules.common.config.SecurityConfig;
import com.carful.xigua.modules.common.util.SecurityContextUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Arrays;

/**
 * uri 权限验证
 *
 * @author Administrator
 * Date 2024/2/7 10:20
 * Description
 */

@Component("UriPermissionHandler")
public class UriPermissionHandler implements PermissionHandler<String, Object> {
    @Autowired
    private SecurityContextUtils securityContextUtils;

    @Override
    public boolean isPre(String target, Object... args) {
        if (!StringUtils.hasText(target)) return false;
        return Arrays.stream(target.split(",")).anyMatch(a -> a.startsWith("uri"));
    }

    @Override
    public boolean isPost(Object returnObject, Object... args) {
        return true;
    }

    @Override
    public boolean preHandle(String target, Object... args) {
//        if (!isPre(target, args)) {
//            return false;
//        }
        // 获取URL
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String uri = request.getRequestURI();
        String method = request.getMethod();
        SecurityConfig.LoginUserDetails loginUserDetails = securityContextUtils.getLoginUserDetails();
        return loginUserDetails.getAuthorities().stream().anyMatch(a -> {
            String[] split = a.getAuthority().split(":");
            return (uri.startsWith(split[0]) || uri.matches(split[0])) && (split.length <= 1 || split[1].matches("|" + method));
        });
    }

    @Override
    public boolean postHandle(Object returnObject, Object... args) {
        return true;
    }
}
